/**
 * Created by hy on 2017/3/10.
 */
import { SAVE_APPLY, UPDATE_CURRENT_APPLY_INDEX, DELETE_APPLY } from '../mutations-types'
import { keys, get } from '../../utils/localstorages'

const state = {
  /**
   * {
   *  gamePreviewId: number,
   *  version: ''
   * }
   */
  applyList: get({key: keys.applyList, defaultVal: []}),
  currentApplyIndex: 0
}

const mutations = {
  [SAVE_APPLY] (state, payload) {
    const index = state.applyList.map(a => a.gamePreviewId).indexOf(payload.gamePreviewId)
    const existRecord = index >= 0 ? state.applyList[index] : null
    if (!existRecord) {
      state.applyList.push(payload)
    } else {
      state.applyList[index] = Object.assign({}, existRecord, payload)
    }
  },
  [UPDATE_CURRENT_APPLY_INDEX] (state, payload) {
    state.currentApplyIndex = payload
  },
  [DELETE_APPLY] (state, payload) {
    for (let index = 0; index < state.applyList.length; index++) {
      if (+state.applyList[index].gamePreviewId === +payload) {
        state.applyList.splice(index, 1)
        index--
      }
    }
  }
}
const getters = {
  currentApply (state) {
    return state.applyList.length > 0 ? state.applyList[state.currentApplyIndex] : null
  }
}
const actions = {
  saveApply ({commit}, payload) {
    commit(SAVE_APPLY, payload)
  },
  clearApply ({commit}, payload) {
    commit(DELETE_APPLY, payload)
  },
  findApply ({state}, payload) {
    const apply = state.applyList.filter(a => a.gamePreviewId === payload)[0] || null
    return apply ? Promise.resolve(apply) : Promise.reject(null)
  },
  deleteApplyGroupValues ({commit}, payload) {
    const {gamePreviewId, editIndex, groupIndex} = payload
    const apply = state.applyList.filter(a => +a.gamePreviewId === +gamePreviewId)[0] || null
    if (!apply) {
      console.log('apply record not found')
      return
    }
    console.log(apply)
    apply.groups[groupIndex].list.splice(editIndex, 1)
    commit(SAVE_APPLY, apply)
  },
  updateApplyGroupValues ({commit}, payload) {
    const {gamePreviewId, editIndex, groupIndex, values} = payload
    const apply = state.applyList.filter(a => +a.gamePreviewId === +gamePreviewId)[0] || null
    if (!apply) {
      console.log('apply record not found')
      return
    }
    if (+editIndex >= 0) {
      apply.groups[groupIndex].list[+editIndex] = values
    } else {
      apply.groups[groupIndex].list.push(values)
    }
    commit(SAVE_APPLY, apply)
  },
  updateCurrentApplyIndex ({commit}, payload) {
    commit(UPDATE_CURRENT_APPLY_INDEX, payload)
  }
}
export default {
  state,
  mutations,
  getters,
  actions
}
